package com.qlc_demo_api.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.io.IOUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {
    // 日志对象
    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    // utf-8字符编码
    public static final String CHARSET_UTF_8 = "UTF-8";


    // HTTP内容类型。
    public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";
    // HTTP内容类型。相当于form表单的形式，提交数据
    public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";

    // HTTP内容类型。相当于form表单的形式，提交数据
    public static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8";

    // 连接管理器
    private static PoolingHttpClientConnectionManager pool;

    // 请求配置
    private static RequestConfig requestConfig;

    /**
     * gson对象
     */
    static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();

    static {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            // 配置同时支持 HTTP 和 HTPPS
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
            // 初始化连接管理器
            pool = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            // 将最大连接数增加到200，实际项目最好从配置文件中读取这个值
            pool.setMaxTotal(200);
            // 设置最大路由
            pool.setDefaultMaxPerRoute(2);
            // 根据默认超时限制初始化requestConfig
            int socketTimeout = 10000;
            int connectTimeout = 10000;
            int connectionRequestTimeout = 10000;
            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
                    .setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
        } catch (NoSuchAlgorithmException e) {
            logger.error("依赖缺失： ", e);
        } catch (KeyStoreException e) {
            logger.error("证书存贮： ", e);
        } catch (KeyManagementException e) {
            logger.error("证书管理： ", e);
        }
        // 设置请求超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000)
                .setConnectionRequestTimeout(50000).build();
    }

    public static CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = HttpClients.custom()
                // 设置连接池管理
                .setConnectionManager(pool)
                // 设置请求配置
                .setDefaultRequestConfig(requestConfig)
                // 设置重试次数
                .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).build();
        return httpClient;
    }

    /**
     * 发送Post请求
     * @param httpPost
     * @return
     */
    private static String sendHttpPost(HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        // 响应内容
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.
            httpClient = getHttpClient();
            // 配置请求信息
            httpPost.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpPost);
            // 得到响应实例
            HttpEntity entity = response.getEntity();

            // 可以获得响应头
            // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
            // for (Header header : headers) {
            // logger.info(header.getName());
            // }

            // 得到响应类型
            // logger.info(ContentType.getOrDefault(response.getEntity()).getMimeType());

            // 判断响应状态
            if (response.getStatusLine().getStatusCode() >= 300) {
                throw new Exception(
                        "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
            }

            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            logger.error("http post method exception:", e);
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("关闭http client 发生异常：", e);
            }
        }
        return responseContent;
    }

    /**
     * 发送Get请求
     * @param httpGet
     * @return
     */
    private static String sendHttpGet(HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        // 响应内容
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.
            httpClient = getHttpClient();
            // 配置请求信息
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpGet);
            // 得到响应实例
            HttpEntity entity = response.getEntity();

            // 可以获得响应头
            // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
            // for (Header header : headers) {
            // System.out.println(header.getName());
            // }

            // 得到响应类型
            // System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());

            String mimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
            // 判断响应状态
            if (response.getStatusLine().getStatusCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is "
                        + response.getStatusLine().getStatusCode());
            }

            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                logger.info("请求数据类型： mimeType = {}", mimeType);
                //判断是否流数据
//                if(mimeType.contains("stream") || mimeType.contains("image")) {
//                    InputStream in = response.getEntity().getContent();
//                    return null;
//                }
                responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
                EntityUtils.consume(entity);
            }

        } catch (Exception e) {
            logger.error("http get method exception:", e);
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("关闭http client 发生异常：", e);
            }
        }
        return responseContent;
    }

    public static void writeResponse(HttpServletResponse response,
                                     String contentType, String encoding, String data) {
        response.setContentType(contentType);
        response.setCharacterEncoding(encoding);
        try {
            IOUtils.write(data, response.getOutputStream(), encoding);
        } catch (IOException e) {
            logger.error("写数据到Response，发生异常：", e);
            e.printStackTrace();
        }
    }

    /**
     * 流数据写入response
     * @param data
     * @param response
     * void
     */
    public static void writeResponse(HttpServletResponse response, String data) {
        writeResponse(response, CONTENT_TYPE_TEXT_HTML, CHARSET_UTF_8, data);
    }

    /**
     * 流数据写入response
     * @param in
     * @param response
     * void
     */
    private static void writeResponse(InputStream in, String fileName, HttpServletResponse response) {
        try {
            fileName = URLEncoder.encode(fileName,"UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;" + "filename*=UTF-8''" + fileName);
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("UTF-8");
        OutputStream out = null;
        BufferedInputStream bins = null;
        BufferedOutputStream bouts = null;
        try {
            // 放到缓冲流里面
            bins = new BufferedInputStream(in);
            out = response.getOutputStream();
            bouts = new BufferedOutputStream(out);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            // 开始向网络传输文件流
            while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
                bouts.write(buffer, 0, bytesRead);
            }
            bouts.flush();
        } catch (IOException e) {
            logger.error("读写数据异常：", e);
        }finally {
            try {
                if (null != out) {
                    out.close();
                }
                if (null != in) {
                    in.close();
                }
                if (null != bins) {
                    bins.close();
                }
                if (null != bouts) {
                    bouts.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送 get请求
     * @param httpUrl
     */
    public static String sendHttpGet(String httpUrl) {
        // 创建get请求
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendHttpGet(httpGet);
    }

    /**
     * 将map集合的键值对转化成：key1=value1&key2=value2 的形式
     * @param params 需要转化的键值对集合
     * @return 字符串
     */
    public static String convertStringParamter(Map<String, String> params) {
        StringBuffer parameterBuffer = new StringBuffer();
        if (params != null) {
            Iterator<String> iterator = params.keySet().iterator();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                if (params.get(key) != null) {
                    value = (String) params.get(key);
                } else {
                    value = "";
                }
                parameterBuffer.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
        }
        return parameterBuffer.toString();
    }

    /**
     * 将map集合的键值对转化成 NameValuePair
     * @param params
     * @return
     */
    public static List<NameValuePair> convertNameValuePairParamter(Map<String, Object> params) {
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        if (params != null) {
            Iterator<String> iterator = params.keySet().iterator();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                if (params.get(key) != null) {
                    if(StringUtils.equalsIgnoreCase(key, "orderDetailList")) {
                        Object object = params.get(key);
                        String jsonString = gson.toJson(object);
                        value = jsonString;
                    }else {
                        value = String.valueOf(params.get(key));
                    }
                } else {
                    value = "";
                }
                nameValuePairs.add(new BasicNameValuePair(key, value));
            }
        }
        return nameValuePairs;
    }

    /**
     * 发送 post请求
     * @param httpUrl 地址
     */
    public static String sendHttpPost(String httpUrl) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        return sendHttpPost(httpPost);
    }

    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param params 参数(格式:key1=value1&key2=value2)
     */
    public static String sendHttpPost(String httpUrl, String params) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            // 设置参数
            if (params != null && params.trim().length() > 0) {
                StringEntity stringEntity = new StringEntity(params, Consts.UTF_8);
                stringEntity.setContentType(CONTENT_TYPE_FORM_URL);
                httpPost.setEntity(stringEntity);
            }
        } catch (Exception e) {
            logger.error("执行http post 请求["+httpUrl+"]，参数["+params+"]，发生异常：", e);
        }
        return sendHttpPost(httpPost);
    }

    /**
     * 发送 post请求
     * @param params 参数
     */
    public static String sendHttpPost(String httpUrl, Map<String, String> params) {
        String parem = convertStringParamter(params);
        return sendHttpPost(httpUrl, parem);
    }

    /**
     * 发送 post请求
     * @param params 参数
     */
    public static String sendHttpPostUrlEncode(String httpUrl, Map<String, Object> params) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            // 设置参数
            List<NameValuePair> parameters = convertNameValuePairParamter(params);
            if(null != parameters && !parameters.isEmpty()) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, Consts.UTF_8);
                entity.setContentType(CONTENT_TYPE_FORM_URL);
                httpPost.setEntity(entity);
            }
        } catch (Exception e) {
            logger.error("执行http post[JSON格式] 请求[" + httpUrl + "]，参数[" + params + "]，发生异常：", e);
        }
        return sendHttpPost(httpPost);
    }

}
